<template>
  <a-drawer
    :title="miniDB.title"
    placement="right"
    :visible="miniDB.visible"
    :width="miniDB.width"
    ref="aa"
    :after-visible-change="afterVisibleChange"
    @close="onClose"
  >
    <div v-if="this.miniDB.flag === '1'">
      <div style="display: inline-flex; margin: 10px; align-items: center" v-if="states">
        <span style="width: 100px">项目名称</span
        ><a-input v-model.trim="itemName" allow-clear style="width: 225px; margin-right: 10px"></a-input>
        <span style="width: 100px; margin: 0 5px">退款类型</span
        ><a-select
          style="margin: 0 10px; width: 180px"
          placeholder="请选择类型"
          v-model.trim="classId"
          allow-clear
          @change="ChangeState"
        >
          <a-select-option v-for="item in RefundType" :key="item.id" :isdisabled="item.label" :value="item.label">
            <div>{{ item.value }}</div>
          </a-select-option>
        </a-select>
        <a-button @click="search" @keyup.enter="search">查询</a-button>
      </div>
      <a-table 
        @expand="ca"
        :row-selection="rowSelections"
        :expanded-row-keys="ExpandedRowKeys"
        :expandIcon="RIcon"
        :rowKey="
          (record, index) => {
            return record.onlyId
          }
        "
        class="components-table-demo-nested"
        :columns="cloumns"
        :dataSource="data"
        :loading="loading" 
        @change="paginationChange"
        :rowClassName="setRowClassName"
      >

        <!-- 支付方式 -->
        <template slot="refundMethod" slot-scope="text" style="padding:0 16px;">
          <div v-html="text" style="text-align:left">{{text}}</div>
        </template>
        <!-- 其他方式 -->
        <template slot="otherType" slot-scope="text">
          <div v-html="text" style="text-align:left">{{text}}</div>
        </template>
        
        

        <div slot="expandedRowRender" slot-scope="record">
          <a-table  
            :row-selection="rowSelectionsSmallTable" 
            

            id="innerTable"
            :customRow="clickInner"
            :columns="innerColumns"
            :dataSource="record.packageList"
            :pagination="false"
            :rowKey="(record,index) => record.onlyId"
            :rowClassName="setRowClassName"
          ></a-table>
        </div>
      </a-table>
    </div>
    <div v-else>
      <a-table
        v-if="state"
        :row-selection="rowSelection"
        :columns="cloumns"
        :data-source="data"
        :rowKey="
          (record, index) => {
            return record.onlyId
          }
        "
        :pagination="false"
        key="index"
        :rowClassName="setRowClassName"
      ></a-table>
    </div>
  </a-drawer>
</template>
<script>
import { getPro, getYc, getYj } from '@/api/cashier/cashier'
export default {
  props: {
    miniDB: {},
    filterData: Array
  },
  watch: {
    
  },
  computed: {
    rowSelections() {
      if(this.miniDB.flag == '1'){
        return {
          // columnTitle:'',hideDefaultSelections:true
          onChange: (selectedRowKeys, selectedRows, state, record) => { 
            // for (var i = 0; i < this.data.length; i++) {
            //   for (var j = 0; j < selectedRowKeys.length; j++) {
            //     if (this.data[i].SID === selectedRowKeys[j]) {
            //       this.$emit('getDetail', selectedRows, this.miniDB.flag)
            //       this.data.splice(i, 1) //加了数据后删除数组对应内容
            //       selectedRowKeys = []
            //       selectedRows = [] 
            //     }
            //   }
            // } 
            this.$emit('getDetail', selectedRows, this.miniDB.flag)
          },
          getCheckboxProps: (record) => ({
            props: {
              disabled: record.refundable == 0 || record.packageList!=undefined,
              defaultChecked: this.filterData.find(elemt => {  
                return record.onlyId == elemt.onlyId
              }) != undefined
            },
          }),
        }
      }
      
    },
    rowSelection() {
      if(this.miniDB.flag !== '1'){
        return {
          onChange: (selectedRowKeys, selectedRows, state) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows, state, 'ca')
            if (selectedRowKeys) {
              this.$emit('getDetail', selectedRows, this.miniDB.flag)
            }
          },
          getCheckboxProps: (record) => ({
            props: {
              disabled: record.offsetAmtNo == 0,
              defaultChecked: this.filterData.find(elemt => {  
                return record.onlyId == elemt.onlyId
              }) != undefined
                
            },
          }),
        }
      }
    },
    // 项目里面的展开列表数据的勾选
    rowSelectionsSmallTable(){
      if(this.miniDB.flag == '1'){
        return { 
          onSelect: (record, selected, selectedRows, nativeEvent) => {
             
           
            let boolD = this.filterData.find(item => {
              return item.onlyId == record.onlyId
            })  
            if(boolD != undefined){
              this.$emit('getDetail', record, this.miniDB.flag, 'remove')
            }else{
              this.$emit('getDetail', record, this.miniDB.flag, 'productList')
            }
            
          },
          onChange: (selectedRowKeys, selectedRows) => { 
        
            // let idArr = []
            // this.filterData.map(item => {
            //   idArr.push(item.onlyId)
            // })
            // // 过滤不存在的数据
            // let newData = selectedRows.filter(item => {
            //   return idArr.indexOf(item.onlyId) == -1
            // })
            
            // // 新增
            // newData.map(item => {
            //   this.$emit('getDetail', item, this.miniDB.flag, 'productList')
            // })
            

            
            
          },
          getCheckboxProps: (record) => ({
            props: {
              disabled: record.refundable == 0,
              defaultChecked: this.filterData.find(elemt => {  
                return record.onlyId == elemt.onlyId
              }) != undefined
                
            },
          }),
          
        }
      }
    },

     
  },
  data() {
    return { 
      selectedRowKeysData: [],
      states: true,
      state: true,
      ExpandedRowKeys: [],
      classId: '',
      RefundType: [
        { id: 1, value: '已治疗退款', label: '1' },
        { id: 2, value: '未治疗退款', label: '0' },
      ],
      innerColumns: [
        {
          title: '项目名称',
          key: 'itemName',
          align: 'center',
          dataIndex: 'itemName',
          // width: 150,
          // ellipsis: true
        },
        {
          title: '可退次数',
          key: 'refundablerqty',
          align: 'center',
          dataIndex: 'refundablerqty',
          // width: 150,
          // ellipsis: true
        },
        {
          title: '实收金额',
          key: 'paidAmt',
          align: 'center',
          dataIndex: 'paidAmt',
        },
        {
          title: '可退金额',
          key: 'refundable',
          align: 'center',
          dataIndex: 'refundable',
          customRender: (money) => {
            if(Number(money) > 0){
              return <span style="color:#4e84a3;font-weight:700">{money}</span>
            }else{
              return <span style="color:rgb(202 202 202);">{money}</span>
            } 
          }
        },
        {
          title: '可退增值金',
          key: 'retreatitemGold',
          align: 'center',
          dataIndex: 'retreatitemGold',
          customRender: (retreatitemGold) => {
            if (retreatitemGold == 0) {
              return '0'
            } else if (!retreatitemGold) {
              return '-'
            } else {
              refundable
            }
          },
        },
        {
          title: '可退积分',
          key: 'jf',
          align: 'center',
          dataIndex: 'jf',
          customRender: (jf) => {
            if (jf == 0) {
              return '0'
            } else if (!jf) {
              return '-'
            } else {
              jf
            }
          },
        },
      ], 

      itemName: '',
      searchDB: [{ id: 0, label: '', slot: 'name' }],
      refundState: [],
      cloumns: [
        
        {
          title: '成交日期',
          key: 'chargeDate',
          align: 'center',
          dataIndex: 'chargeDate',
          customRender: (chargeDate) => {
            if (!chargeDate) {
              return '-'
            } else {
              return chargeDate.split(' ')[0]
            }
          },
        },
        {
          title: '项目名称',
          key: 'itemName',
          align: 'center',
          width: 150,
          ellipsis: true,
          dataIndex: 'itemName',
          customRender: (itemName) => {
            if (!itemName) {
              return '-'
            } else {
              return itemName
            }
          },
        },
        {
          title: '剩余数量',
          key: 'refundablerqty',
          align: 'center',
          dataIndex: 'refundablerqty',
       
        },
        {
          title: '营收',
          align: 'center',
          key: 'paidAmt',
          dataIndex: 'paidAmt',
         
        },
        {
          title: '支付方式',
          align: 'center',
          key: 'refundMethod',
          dataIndex: 'refundMethod', 
        },
        {
          title: '可退金额',
          align: 'center',
          key: 'refundable',
          dataIndex: 'refundable',
          customRender: (money) => {
            if(Number(money) > 0){
              return <span style="color:#4e84a3;font-weight:700">{money}</span>
            }else{
              return <span style="color:rgb(202 202 202);">{money}</span>
            } 
          }
     
        },
        {
          title: '可退增值金',
          key: 'retreatitemGold',
          align: 'center',
          dataIndex: 'retreatitemGold',
       
        },
        {
          title: '可退积分',
          key: 'jf',
          align: 'center',
          dataIndex: 'jf',
          
        },
      ],
      queryParams: {
        pageSize: 1,
        pageNum: 20,
      },
      data: [],
      loading: false,
    }
  },
  mounted() {
    this.ca() 
  },
  methods: {
    // 点击分页触发的事件
    paginationChange(){
      this.$nextTick(() => {
        let target = document.querySelectorAll('.ant-table-expanded-row') 
        console.log('target:',target)
        for (var i = 0; i < target.length; i++) { 
          target[i].childNodes[1].colSpan = target[i].childNodes[1].colSpan = 13
          target[i].childNodes[1].style = target[i].childNodes[1].style = "padding:0;"
        }
      })
    },
    
    clickInner(record) {
      return {
        on: {
          dblclick: () => {
            console.log(record, '深层表格')
            
            // let boolD = this.filterData.find(item => {
            //   return item.onlyId == record.onlyId
            // })  
            // if(boolD != undefined){
            //   this.$emit('getDetail', record, this.miniDB.flag, 'remove')
            // }else{
            //   this.$emit('getDetail', record, this.miniDB.flag, 'productList')
            // }
          }
            
        },
      }
    },
    // 底下列表选中的数据添加背景色
    setRowClassName(record,index){ 
      let idArr = []
      this.filterData.map(item => {
        idArr.push(item.onlyId)
      })
      return idArr.indexOf(record.onlyId) != -1 ? 'clickRowStyle' : ''
      
    },
    async ca(val, record) {
      console.log('a') 
      this.boxData = []
      if (val) {
        this.ExpandedRowKeys = []
        this.ExpandedRowKeys.push(record.onlyId)
        
        
        console.log(this.ExpandedRowKeys)
        setTimeout(() => {
          this.$nextTick(() => {
            let target = document.querySelectorAll('.ant-table-expanded-row')
            console.log(target)
            for (var i = 0; i < target.length; i++) {
              console.log(target[i].childNodes[1].colSpan)
              target[i].childNodes[1].colSpan = target[i].childNodes[1].colSpan = 13
               target[i].childNodes[1].style = target[i].childNodes[1].style = "padding:0;"
            }
          })  
        }, 50);
        
        
        
      } else {
        this.ExpandedRowKeys = []
      }
      
    },
    ChangeState(val) {
      console.log(val)
      this.classId = val 
    },
    clicks(record) {
      return {
        on: {
          dblclick: () => {
            if (!record.packageList) {
              const db = record
              this.$emit('getDetail', db, this.miniDB.flag)
            } else {
              this.$message.error('该项数据只能选择子项进行退款操作！')
            }
          },
        },
      }
    },
    onClose() {
      this.miniDB.flag = 0
      this.miniDB.visible = false
      this.states = false
    },
    search() {
      this.loading = true
      let queryParams = {
        pageSize: 20,
        pageNum: 1,
        itemName: undefined,
        classId: this.classId,
        id: undefined,
      }
      queryParams.id = this.miniDB.id
      queryParams.itemName = this.itemName 
      getPro(Object.assign(queryParams)).then((res) => {
        this.loading = false
        if (res.code.toString() !== '200' && res.code) return this.$message.error(res.msg)
        this.$message.success(res.msg)
        // 新增的时候获取的数据根据选中的数据进行旁判断，如果存在就过滤
        // let itemIdArr = []
        // this.filterData.map(elemt => {
        //   itemIdArr.push(elemt.itemId)
        // })
        // console.log(itemIdArr)
        // let newRows = res.rows.filter((item) => {
        //   return itemIdArr.indexOf(item.itemId) == -1
        // })

        let newRows = res.rows
        this.$nextTick(() => {
          newRows.forEach((item, index) => {
            item.SID = item.itemId + index //表rowkey的字段 
            // item.sId = item.itemId + index  
            if (item.packageList!==undefined) { 
              item.itemName = item.packageList.map((item) => item.packageName)[0]
            } else {
              item.packageList = null
              item.itemName = item.name || item.itemName
            }
          })
          this.data = newRows
          this.subData = newRows
        })
        
      })
    },
    RIcon(props) {
      if (props.record.packageList) {
        if (props.expanded) {
          console.log(props.expanded)
          return (
            <a
              onClick={(e) => {
                console.log('123123')
                props.onExpand(props.record, e)
              }}
            >
              <a-icon type="down"></a-icon>
            </a>
          )
        } else {
          return (
            <a
              onClick={async (e) => {
                props.onExpand(props.record, e)
                console.log('1231231')
              }}
            >
              <a-icon type="right"></a-icon>
            </a>
          )
        }
      } else {
        return <span></span>
      }
    },
    async afterVisibleChange(val) {

      // rowSelections.hideDefaultSelections:true
      this.state = true
      this.states = true
      console.log(val, this.miniDB.id, this.miniDB)
      if (!val) {
        this.data = []
        console.log('表格重置')
        this.state = false
        this.states = false
        this.miniDB.flagif
      } else if (val) {
        //当状态为真的时候才会走请求
        this.classId = ''
        this.itemName = ''
        this.loading = true //load状态
        this.data = []
        let queryParams = {
          pageSize: 20,
          pageNum: 1,
          id: undefined,
          customerId: undefined,
        }
        if (this.miniDB.flag === '1') {
          console.log('退项目')
          //退项目
          if (this.miniDB.id && val) {
            this.cloumns = [
              // {
              //   title: '序号', 
              //   align: 'center', 
              //   dataIndex: 'xh', 
              //   scopedSlots: { customRender: 'xh' },
              // },
              {
                title: '成交日期',
                key: 'chargeDate',
                align: 'center',
                width: 120,
                dataIndex: 'chargeDate',
                customRender: (chargeDate) => {
                  if (!chargeDate) {
                    return '-'
                  } else {
                    return chargeDate.split(' ')[0]
                  }
                },
              },
              {
                title: '项目名称',
                key: 'itemName',
                align: 'center',
                width: 150,
                // ellipsis: true,
                dataIndex: 'itemName',
                customRender: (itemName) => {
                  if (!itemName) {
                    return '-'
                  } else {
                    return itemName
                  }
                },
              },
              {
                title: '剩余数量',
                key: 'refundablerqty',
                align: 'center',
                
                dataIndex: 'refundablerqty',
              },
              {
                title: '营收',
                align: 'center',
                key: 'paidAmt',
                dataIndex: 'paidAmt',
              },
              {
                title: '支付方式',
                // align: 'center',
                key: 'refundMethod',
                dataIndex: 'refundMethod',
                scopedSlots: { customRender: 'refundMethod' }, 
              },
              {
                title: '其他方式',
                // align: 'center',
                key: 'otherType',
                dataIndex: 'otherType',
                scopedSlots: { customRender: 'otherType' }, 
              },
              
              {
                title: '可退金额',
                align: 'center',
                key: 'refundable',
                dataIndex: 'refundable',
                customRender: (money) => {
                  if(Number(money) > 0){
                    return <span style="color:#4e84a3;font-weight:700">{money}</span>
                  }else{
                    return <span style="color:rgb(202 202 202);">{money}</span>
                  } 
                }
              },
              {
                title: '可退增值金',
                key: 'retreatitemGold',
                align: 'center',
                dataIndex: 'retreatitemGold',
              },
              {
                title: '可退积分',
                key: 'jf',
                align: 'center',
                dataIndex: 'jf',
              },
            ]
            queryParams.id = this.miniDB.id
            getPro(Object.assign(queryParams))
              .then((res) => {
                console.log(res)
                this.loading = false
                if (res.code && res.code.toString() !== '200') {
                  this.$message.error(res.msg || res.message)
                  return
                }

                // 新增的时候获取的数据根据选中的数据进行旁判断，如果存在就过滤
                // let itemIdArr = []
                // this.filterData.map(elemt => {
                //   itemIdArr.push(elemt.itemId)
                // })
                // console.log(itemIdArr)
                // let newRows = res.rows.filter((item) => {
                //   return itemIdArr.indexOf(item.itemId) == -1
                // })
                // console.log(newRows)

                let newRows = res.rows
                this.$nextTick(()=>{
                  newRows.forEach((item, index) => {
                    //洗数据
                    item.SID = item.itemId + index //表rowkey的字段 
                    if (item.packageList!==undefined) { 
                      item.itemName = item.packageList.map((item) => item.packageName)[0]
                    } else {
                      item.packageList = null
                      item.itemName = item.itemName
                    }
                  })
                  this.$message.success(res.msg)
                  this.data = newRows
                  this.subData = newRows
                })
                
              })
              .catch((err) => {
                console.log(err)
              })
          }
        } else if (this.miniDB.flag === '2') {
          //退卡（预存款）
          this.cloumns = [
            {
              title: '充值日期',
              dataIndex: 'rpDate',
              key: 'rpDate',
              width: '200px',
              align: 'center',
            },
            {
              title: '名称',
              dataIndex: 'name',
              key: 'name',
              width: '200px',
              align: 'center',
            },
            {
              title: '总金额',
              dataIndex: 'rpMmt',
              key: 'rpMmt',
              width: '200px',
              align: 'center',
            },
            {
              title: '可退金额',
              dataIndex: 'offsetAmtNo',
              key: 'offsetAmtNo',
              width: '200px',
              align: 'center',
              customRender: (money) => {
                if(Number(money) > 0){
                  return <span style="color:#4e84a3;font-weight:700">{money}</span>
                }else{
                  return <span style="color:rgb(202 202 202);">{money}</span>
                } 
              }
            },
            {
              title: '已核销金额',
              dataIndex: 'offsetAmt',
              key: 'offsetAmt',
              width: '200px',
              align: 'center',
            },
          ]
          queryParams.customerId = this.miniDB.id
          queryParams.type = '1'
          console.log('准备退卡', queryParams)
          getYc(Object.assign(queryParams)).then((res) => {
            this.loading = false
            if (res.code && res.code.toString() !== '200') {
              return this.message.error(res.msg || res.message)
            } else {
              res.rows.forEach((item) => {
                item.name = '退预存款'
              })
              this.data = res.rows
            }
          })
        }
      }
    },
  },
}
</script>
<style scoped lang="less">
/deep/ .ant-table-footer {
  height: 50px;
  overflow: hidden;
}
/deep/ #innerTable .ant-table-thead {
  background-color: #f0faff !important;
}
/deep/ #innerTable .ant-table-thead > tr > th {
  background: none !important;
}
/deep/ .ant-table-expanded-row > td:first-child {
  display: none !important;
}
/deep/ .ant-table-row-level-0 {
  position: relative;
  a{
    position: absolute;
    left: 76px;
    top: 37%;
  }
}
/deep/ .add-table-style .ant-table-tbody > tr > td {
  padding: 10px 16px !important;
   
}

/deep/ .ant-table-header-column{
  .ant-checkbox{
    display: none !important;
  }
}
/deep/ .ant-checkbox-disabled{
  display: none;
}

/deep/ .clickRowStyle,
.clickRowStyle:hover>td,
.clickRowStyle>td>span{
  background-color: #4e84a3 !important;
  color: #fff !important;
}
/deep/ .clickRowStyle> td, 
.clickRowStyle>td, 
.clickRowStyle:hover > td, 
.clickRowStyle:hover> td{
  background-color: #4e84a3 !important;
  color: #fff !important;
}
/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
::-webkit-scrollbar{
  width: 16px;
  height: 16px;
}

/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track{
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
  border-radius: 10px;
  background-color: red;
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb{
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
  background-color: #555;
}
/deep/.ant-checkbox-checked .ant-checkbox-inner {
  background-color: #fff !important;
  border-color: #fff !important; 
}
/deep/ .ant-checkbox-checked .ant-checkbox-inner::after{
  border-color: #4e84a3 !important;
}
/deep/ .components-table-demo-nested{
  .ant-table-tbody{
    tr>td:nth-child(7),
    tr>td:nth-child(8){
      padding: 0 16px !important;
    }
  }
}
</style>